package ai.people.platform.archives.service.listener;

import ai.people.netmon.framework.domain.gang.construction.entity.LabelLibAccount;
import ai.people.netmon.framework.domain.gang.construction.request.LabelLibAccountExcel;
import ai.people.netmon.utils.NumeralPool;
import ai.people.platform.archives.service.LabelLibAccountService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhenglin
 * @date 2022/7/22
 */
@Slf4j
public class LabelLibAccountExcelListener implements ReadListener<LabelLibAccountExcel> {

    private LabelLibAccountService service;

    private List<LabelLibAccountExcel> list = new ArrayList<>();
    private List<Integer> errorLine = new ArrayList<>();

    private Long labelLibId;

    int total = 0;

    public LabelLibAccountExcelListener(LabelLibAccountService service, List<Integer> errorLine, Long labelLibId) {
        this.service = service;
        this.errorLine = errorLine;
        this.labelLibId = labelLibId;
    }

    @Override
    public void invoke(LabelLibAccountExcel data, AnalysisContext context) {
        if (Objects.nonNull(data)) {
            if (StringUtils.isNotBlank(data.getPlatform()) && StringUtils.isNotBlank(data.getAccount()) && StringUtils.isNotBlank(data.getUrl())) {
                list.add(data);
                if (list.size() >= NumeralPool.ONE_THOUSAND) {
                    save();
                }
            } else {
                errorLine.add(context.readRowHolder().getRowIndex() + 1);
            }
        }
    }

    private void save() {
        List<LabelLibAccount> saveList = new ArrayList<>(NumeralPool.ONE_THOUSAND);
        for (LabelLibAccountExcel excel : list) {
            saveList.add(new LabelLibAccount(excel, labelLibId));
        }
        if (CollectionUtils.isNotEmpty(saveList)) {
            service.saveBatchCustom(saveList);
            total += saveList.size();
        }
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        save();
        log.info("标签库账号导入完成 解析条数:{},错误条数:{}", total, errorLine.size());
    }
}
